#pragma once
#include "Runnable.h"
#include "RunnableThread.h"
#include "Networking.h"
#include "Engine/EngineTypes.h"

DEFINE_LOG_CATEGORY_STATIC(LogRMTBSocketThread, Warning, All);
DECLARE_MULTICAST_DELEGATE_OneParam(FOnMessageDelegate, FString)

class ISocketSubsystem;

class FRMTBSocketThread : public FRunnable
{
	FRunnableThread* Thread;
	FSocket* Socket;
public:
	FRMTBSocketThread(FString url,int32 port);
	~FRMTBSocketThread();

	virtual bool Init();
	virtual uint32 Run();
	virtual void Stop();
public:
	FOnMessageDelegate OnMessage;
	void SendMessage(FString msg);
private:
	bool FormatIP4ToNumber(const FString& TheIP, uint8(&Out)[4]);
	void RecvData();
	void BroadcastMessage();
	void trySendMessage();
	FString StringFromBinaryArray(TArray<uint8> BinaryArray);
	FString PeddingMessage;
	FString RecvMessage;
	mutable FCriticalSection mCritical;

	FString ServerURL;
	int32 ServerPort;
	ISocketSubsystem* SocketSubsystem;
};